package com.kgc.service.Impl.user;

import com.kgc.entity.User;
import com.kgc.dao.mapper.user.UserMapper;
import com.kgc.service.interf.user.UserService;
import com.kgc.util.SecretUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @author hyj
 * @time 2024/4/1 14:37
 * @describe
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private TransactionTemplate transactionTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer register(User user) throws NoSuchAlgorithmException {
        Integer i1 = userMapper.selectByUsername(user.getUsername());
        Integer i2 = userMapper.selectByEmail(user.getEmail());
        if (i1 != null) {
            // 该用户名已存在
            return 10;
        }
        if (i2 != null) {
            // 该邮箱已注册
            return 20;
        }
        user.setPassword(SecretUtil.md5(user.getPassword()));
        Integer register = userMapper.registerUser(user);
        Integer insert = userMapper.insertUserRoles(user.getEmail());
        // 数据回滚
        if (register + insert != 2) {
            TransactionStatus status = Objects.requireNonNull(transactionTemplate.getTransactionManager()).getTransaction(new DefaultTransactionDefinition());
            status.setRollbackOnly();
        }
        return register + insert;
    }

    @Override
    @Transactional
    public User login(String username, String password) throws NoSuchAlgorithmException {
        Integer i1 = userMapper.selectByUsername(username);
        Integer i2 = userMapper.selectByEmail(password);
        if (i1 == null && i2 == null) {
            // 用户名/邮箱 不存在
            return new User(-1);
        }
        Integer[] i3 = userMapper.selectByEmailAndUsername(username, SecretUtil.md5(password));
        if (i3.length == 0) {
            // 密码错误
            return new User(-2);
        }
        Integer i4 = userMapper.selectStatus(username);
        if (i4 == 0) {
            return new User(-3);
        }
        return userMapper.selectByEmailAndUsernameAndRoleId(username, SecretUtil.md5(password));
    }

    @Override
    public Integer updateUser(String email, String password) throws NoSuchAlgorithmException {
        return userMapper.updateUser(email, SecretUtil.md5(password));
    }

    @Override
    public Integer isExist(String email) {
        return userMapper.selectByEmail(email);
    }
}
